package com.htjx.mall.controllers.commonapi;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.htjx.mall.commons.models.cart.CartItem;


/**
 * 
 * @author Administrator
 */
public class Cart {
	List<CartItem> cartList = new ArrayList<CartItem>();
	/** 商品总价格 **/
	private BigDecimal total = BigDecimal.ZERO;

	public void add(CartItem cartItem) {
		long specId = cartItem.getSpecification_id();
		boolean flag = false;
		for(CartItem item : cartList) {
			if(item.getSpecification_id() == specId) {
				item.setQuantity(item.getQuantity() + cartItem.getQuantity());
				flag = true;
				break;
			}
		}
		if(!flag) {
			cartList.add(cartItem);
		}
		calcTotal();
	}
	
	public void remove(long specificationId) {
		for(int i=0; i < cartList.size(); i++) {
			if(cartList.get(i).getSpecification_id() == specificationId) {
				cartList.remove(i);
			}
		}
		calcTotal();
	}
	
	public void removeAll() {
		cartList.clear();
		calcTotal();
	}
	
	public void calcTotal() {
		this.total = BigDecimal.ZERO;
		for(CartItem item : cartList) {
			this.total = this.total.add(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
		}
	}

	public List<CartItem> getCartList() {
		return cartList;
	}

	public void setCartList(List<CartItem> cartList) {
		this.cartList = cartList;
	}

	public BigDecimal getTotal() {
		return total;
	}

	public void setTotal(BigDecimal total) {
		this.total = total;
	}
	
	public CartItem getItem(long specificationId) {
		for(CartItem item : cartList) {
			if(item.getSpecification_id() == specificationId) {
				return item;
			}
		}
		return null;
	}
	
	public void updateItem(long specificationId, int quantity) {
		for(CartItem item : cartList) {
			if(item.getSpecification_id() == specificationId) {
				item.setQuantity(quantity);
			}
		}
		calcTotal();
	}
}
